import { Directive, OnInit, ElementRef, Renderer } from '@angular/core';
import { LoadingService, LoadingParams } from "./loading.service";

import "./rxjs-operators";

/**
 * 财迷的Loading指令；该指令接收四个定制属性；
 * Loading指令并不直接弹出某类对象，而是在指令所寄宿的元素上增加/去除某个Loading定制类，默认为loading；
 * 
 * 
 * @export
 * @class CmLoadingDirective
 * @implements {OnInit}
 */
@Directive({
  selector: '[cmLoading]',
  inputs: [
    "responseTo",
    "responseToNoTarget",
    "loadingClass",
    "isGlobalLoading"
  ]
})
export class CmLoadingDirective implements OnInit {
  
  /**
   * 该属性必定为输入绑定类，其接受一个字串数组，
   * 如果loading事件源指定的id存在于该数组中，则该loading响应
   * 
   * @type {string[]}
   * @memberOf CmLoadingDirective
   */
  responseTo: string[] = [];
  
  /**
   * 响应Loading时为组件增加的类
   * @memberOf CmLoadingDirective
   */
  loadingClass = "loading";
  
  /**
   * 是否响应匿名Loading，即没有指定任何Id的Loading发起
   * 
   * @type {boolean}
   * @memberOf CmLoadingDirective
   */
  responseToNoTarget: boolean;
  
  /**
   * 是否全局响应Loading，无论匿名或是指定ID，只要有Loading发出该组件即响应
   * 
   * @type {boolean}
   * @memberOf CmLoadingDirective
   */
  isGlobalLoading: boolean;

  constructor(
    private loading: LoadingService,
    private elm: ElementRef,
    private renderer: Renderer
  ) { }

  private setClass(isShowing, id) {
    if (!isShowing && id in this.loading.inLoading && this.loading.inLoading[id] != 0) return;
    this.renderer.setElementClass(this.elm.nativeElement, this.loadingClass, isShowing);
  }

  ngOnInit() {
    this.loading.loadingObs
      .filter(
      (params: LoadingParams) =>
        (this.responseTo.indexOf(params.id) !== -1 ||
          this.isGlobalLoading ||
          (!!this.responseToNoTarget && params.id === undefined)
        )
      )
      .subscribe((params: LoadingParams) => this.setClass(params.toShow, params.id));
  }

}